<template>
  <div class="channelSelect hideScrollBar" ref="scrollEl">
    <!-- 内容部分 -->
    <div :class="{ 'channelSelect-bg': channelList.length > 0 }">
      <!-- 导航 -->
      <NavBar
        isFixed
        :title="$t('pledge.selectChannel')"
        :isTransparent="pageData.whiteTheme"
        :navScorllOffset="60"
        navScorllColor="#FFF"
        :scrollEl="scrollEl"
        isCusRightBtns
        @thresholdChange="(val) => (pageData.whiteTheme = !val)"
      >
        <!-- 客服 -->
        <template #right>
          <img
            class="customerService"
            src="/image/pledge/customerService-icon.svg"
            @click="jumpPage"
          />
        </template>
      </NavBar>
      <!-- 暂无内容 -->
      <div
        v-if="channelList.length === 0"
        class="contentview-notdata items-center"
      >
        <div class="contentview-notdata-img">
          <Images src="/image/assetDetails/not-adta.svg"></Images>
        </div>
        <div class="contentview-notdata-desc">{{ t("mvp.other.zwnr") }}</div>
      </div>
      <div class="content" v-else>
        <!-- 列表 -->
        <div class="box" v-for="(item, index) in channelList" :key="index">
          <div
            v-if="item.title && channelList.length > 1"
            class="box-title items-center"
          >
            <img
              v-if="item.type == 1"
              class="box-title-icon"
              src="/image/pledge/hot-icon.svg"
            />
            {{ item.title }}
          </div>
          <div class="box-list">
            <div
              class="box-item items-center"
              v-for="(channel, idx) in item.list"
              :key="index"
              :style="{
                'border-top':
                  idx === 0 && item.title && channelList.length > 1
                    ? '0.5px solid #e7e9e8'
                    : idx > 0
                    ? '0.5px solid #e7e9e8'
                    : 'none',
                'padding-bottom': idx == item.list.length - 1 ? 0 : '20px',
              }"
              @click="radioChannel(channel)"
            >
              <div class="box-item-left items-center">
                <div class="box-item-left-img">
                  <Images isHttp :src="channel.payImgUrl" />
                </div>
                <div style="flex: 1">
                  <div
                    class="box-item-left-title"
                    :class="{
                      'box-item-left-title-disabled': channel.disabled,
                    }"
                  >
                    {{ channel.payName }}
                  </div>
                  <div
                    class="box-item-left-desc"
                    :class="{ 'box-item-left-desc-disabled': channel.disabled }"
                  >
                    {{ channel.notice }}
                  </div>
                </div>
              </div>
              <!-- 单选 -->
              <div
                class="box-item-right"
                :style="{
                  border: channel.isSelect
                    ? '1px solid #007BFF'
                    : '1px solid #d0d4df',
                }"
              >
                <p
                  :style="{
                    'background-color': channel.isSelect ? '#007BFF' : '#fff',
                  }"
                  class="box-item-right-center"
                  :class="{
                    'box-item-right-center-disabled': channel.disabled,
                  }"
                ></p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 需要 app 桥接 -->
      <div class="footer" v-if="channelList.length > 0">
        <div
          class="footer-btn"
          :class="{
            'footer-btn-disabled': !selectChannel,
          }"
          @click.stop="handleSubmit(1)"
        >
          {{ $t("common.confirm") }}
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="channelSelect">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { getPayChannel } from "@/api/pay";
import { navigateBack, isAndroid, isiOS } from "@/utils";
import { useUserStore } from "~~/store/modules/user";
import { usePageCacheStore } from "~~/store/modules/pageCache";
import { useGlobalStore } from "~~/store/global";
import { sendCommonMessage } from "@/api/log";
import * as MITO from "@zhj1214/qdjk-web";
import { thirdPay, getPayEndSuccessID } from "@/api/pay";
import { JUMPAPPS } from "~/config";

const { t } = useI18n();
const route = useRoute();
console.log("页面参数:", route.query);

// firebase埋点
const firebase = useInitFirebase();
const scrollEl = ref();
const userState = useUserStore();
const pageCache = usePageCacheStore();

const pageData = reactive({
  navBarHeight: 20,
  whiteTheme: true,
});

// 渠道列表
const channelList: any = ref([]);
const globalStore = useGlobalStore();

// 支付渠道: 安卓: 是不是老包,老包 120 渠道不支持,新包都支持;  iOS(只有一个包): 都可以
const isOldApp = computed(() => {
  if (isAndroid.value) {
    return !bridgeVersionCheck(JUMPAPPS().channelPay120);
  } else {
    return false;
  }
});

/**
 * @description: 获取渠道
 * 1. 从 stroe 中获取最近一次充值成功的渠道 id,添加到热门列表中
 */
const getPayChannelRequest = () => {
  channelList.value = [];
  // 1. loading
  showLoadingToast({
    message: `${t("common.requestIng")}...`,
    forbidClick: true,
    duration: 15000,
  });
  try {
    getPayChannel({ cache: true }).then((res) => {
      // console.log("--获取渠道--", res);
      if (res) {
        // 1. 分类
        let otherArr: any = []; // 不推荐
        let tjArr: any = []; // 推荐
        let sxArr: any = []; // 首选
        // 过滤掉不符合条件的
        let sourceArr = res?.pay?.payList.filter((e: any) => {
          let isok = true;
          // 1. 老包不支持 120 渠道
          if (e.payId == 120 && isOldApp.value) {
            isok = false;
          }
          // 2. 根据充值档位,进行过滤
          if (route.query && route.query.cash) {
            // 2.1 如果渠道限额 小于 充值金额-禁用逻辑
            if (
              Number(route.query.cash) > Number(e.rechargeMax || 9999999999)
            ) {
              isok = false;
            }

            // 2.2 如果渠道最低限额 大于 充值金额 - 不显示
            if (e.rechargeMin) {
              if (Number(route.query.cash) < Number(e.rechargeMin)) {
                isok = false;
              }
            }
          }
          return isok;
        });
        // console.log(sourceArr.length, "--sourceArr--", sourceArr);

        sourceArr.forEach((e: any) => {
          if (isOldApp.value && e.payId == 120) {
            return;
          } else {
            // 1. 是否选中
            if (route.query && route.query.payId == e.payId) {
              e.isSelect = true; // 编辑的场景:渠道 id
            } else {
              e.isSelect = false;
            }
            // 2. 如果渠道限额 小于 充值金额-禁用逻辑
            if (route.query && route.query.cash) {
              e.disabled =
                Number(route.query.cash) > Number(e.rechargeMax || 9999999999);
              if (e.disabled) {
                console.log(
                  "充值:",
                  route.query.cash,
                  "最大:",
                  e.rechargeMax || "无上限"
                );
                console.warn("渠道", e.payName, "被禁用.");
              }
            }
            // 3. 数据分类
            if (
              e.recommend == 2 ||
              (userState.$state &&
                userState.$state.lastPayChannelID &&
                userState.$state.lastPayChannelID == e.payId)
            ) {
              if (
                userState.$state &&
                userState.$state.lastPayChannelID &&
                userState.$state.lastPayChannelID == e.payId
              ) {
                sxArr.unshift(e);
              } else {
                sxArr.push(e);
              }
            } else if (e.recommend == 1) {
              tjArr.push(e);
            } else {
              otherArr.push(e);
            }
          }
        });
        // 2.1 热门
        // console.log(sxArr,'--hotArr--',tjArr);
        let hotArr = sxArr.concat(tjArr);
        if (hotArr.length > 3) hotArr = hotArr.splice(0, 3);
        // 2.2 其他
        let hotIds = hotArr.map((e: any) => e.payId);
        otherArr = sxArr.concat(tjArr).concat(otherArr);
        otherArr = otherArr.filter((e: any) => {
          return !hotIds.includes(e.payId);
        });
        // 3. 加工数据
        if (hotArr.length > 0) {
          channelList.value.push({
            type: 1,
            title: t("pledge.hotChannel"),
            list: hotArr,
          });
        }
        if (otherArr.length > 0) {
          channelList.value.push({
            type: 2,
            title: hotArr.length > 0 ? t("pledge.otherChannel") : "",
            list: otherArr,
          });
        }
      }
    });
  } catch (error) {
    MITO.log({
      message: `查询支付渠道失败: getPayChannel`,
      tag: "手动上报",
      level: "high",
      ex: "手动上报",
    });
  }
};

onMounted(() => {
  // 1. 埋点
  firebase?.logEvent("BDC_H5_Pledge_Channel_PUV");
  // 2. 获取渠道
  getPayChannelRequest();
  // console.log('--userState.$state.lastPayChannelID--',userState.$state.lastPayChannelID);
});

// 客服跳转
const jumpPage = () => {
  console.log(route.query.isJumpOpenChat == "1");

  // 联系客服
  if (route.query.isJumpOpenChat == "1") {
    bridge.jumpAppRoute(JUMPAPPS()["openChat"]);
  }
  // 聊天列表
  else {
    bridge.jumpAppRoute(JUMPAPPS()["ChatroomList"]);
  }
};

// 选择的渠道
const selectChannel = ref();

// 单选
const radioChannel = (val: any) => {
  // console.log("单选", val);
  if (val.disabled) return showToast(t("pledge.qcxxz"));
  // 1. 显示
  val.isSelect = true;
  selectChannel.value = val;
  // 3. 其他选项重置
  channelList.value.forEach((element: any) => {
    if (element.list && element.list.length > 0) {
      element.list.forEach((e: any) => {
        if (e.payId != val.payId) e.isSelect = false;
      });
    }
  });
};

// 立即充值
const handleSubmit = () => {
  if (!route.query.cash) return showToast(t("pledge.qxzczje"));
  if (!selectChannel.value) return showToast(t("pledge.qxzczqd"));
  thirdPayApi();
};

// 唤起第三方支付
const loading = ref(false);
const thirdPayApi = debounce(
  async () => {
    // 1. 使用 loading 遮罩
    const toast = showLoadingToast({
      message: `${t("common.requestIng")}...`,
      forbidClick: true,
      duration: 15000,
    });

    try {
      if (loading.value) return;
      loading.value = true;
      // 2. 支付埋点
      firebase?.logEvent("BDC_H5_Pledge_Recharge_payment", {
        sid: (userState.$state && userState.$state.sid) || "未知sid",
        cash: route.query.cash,
      });
      // 3. 创建订单,并跳转支付
      const result = await thirdPay(
        {
          /****** start 自定义参数 start *******/
          // 自定义参数: 2024.04.03 [14:40] Morgan "task":null,"sourceType":4,"sourceId":取对应的任务类型
          task: null,
          sourceType: 4,
          sourceId: route.query.sourceId, // 取对应的任务类型
          /****** end 自定义参数 end *******/
          orderMoney: route.query.cash + "",
          payId: selectChannel.value.payId,
          isNeedPreferential: 1,
          sourceTime: `${new Date().valueOf()}`, // 时间戳
        },
        selectChannel.value.requestUrl ?? "",
        globalStore.$state.packageId
      );
      toast.close();
      if (!result) {
        showToast(t("common.networkAnomaly"));
        sendCommonMessage({ message: `h5创建支付订单失败,result=null` });
      } else if (result.code === 200) {
        if (result.data && result.data?.payUrl) {
          // iOS桥接: 默认浏览器打开,如有安装手动点击跳转,没有这正常加载支付链接
          if (isiOS.value) {
            bridge.defaultBrowserOpen(result.data?.payUrl);
          }
          // 安卓桥接:打开三方 app,如果咩有安装,默认浏览器打开h5
          else {
            bridge.defaultBrowserOpen(result.data?.payUrl);
          }
        } else {
          showToast(t("common.networkAnomaly"));
          sendCommonMessage({ message: `h5创建支付订单失败,payUrl不存在` });
          MITO.log({
            message: `h5创建支付订单失败,payUrl不存在`,
            tag: "手动上报",
            level: "high",
            ex: "手动上报",
          });
        }
      } else {
        if (result.data.errors) {
          showToast(result.data.errors);
        }
        sendCommonMessage({
          message: `支付失败:档位-${route.query.cash}渠道-${JSON.stringify(
            selectChannel.value
          )}错误信息-${result.data.errors}`,
        });
        MITO.log({
          message: `支付失败:档位-${route.query.cash}渠道-${JSON.stringify(
            selectChannel.value
          )}错误信息-${result.data.errors}`,
          tag: "手动上报",
          level: "high",
          ex: "手动上报",
        });
      }
    } catch (error) {
      toast.close();
      sendCommonMessage({ message: `h5支付代码执行失败:${error}` });
      MITO.log({
        message: `支付代码执行失败:${error}`,
        tag: "手动上报",
        level: "high",
        ex: "手动上报",
      });
      console.log(error);
    } finally {
      loading.value = false;
      toast.close();
    }
  },
  1000,
  false
);
</script>
<style lang="scss" scoped>
.channelSelect {
  position: relative;
  background-color: #f0f3fa;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
  margin-bottom: constant(safe-area-inset-bottom);
  margin-bottom: env(safe-area-inset-bottom);
  padding-bottom: var(--safe-area-inset-bottom);

  &-bg {
    background: linear-gradient(
      180deg,
      #bcdbff 0%,
      rgba(244, 249, 254, 0) 100%
    );
    background-size: 100vh 250 * 2px;
    background-repeat: no-repeat;
    margin-bottom: 70 * 2px;
  }
  &-title {
    margin: 20 * 2px 0px 20 * 2px 15 * 2px;
    &-icon {
      width: 20 * 2px;
      height: 20 * 2px;
      margin-right: 8 * 2px;
    }
    &-text {
      color: #141924;
      font-size: 15 * 2px;
      font-weight: 590;
    }
  }
}

.customerService {
  width: 18 * 2px;
  height: 18 * 2px;
}

.content {
  margin-top: 20 * 2px;
}

.box {
  position: relative;
  background: #fff;
  border-radius: 12 * 2px;
  padding: 15 * 2px;
  margin-bottom: 10 * 2px;
  &-title {
    width: 100%;
    color: #141924;
    font-size: 15 * 2px;
    font-weight: 590;
    margin-bottom: 16 * 2px;
    &-icon {
      width: 20 * 2px;
      height: 20 * 2px;
      margin-right: 4 * 2px;
    }
  }

  &-list {
    overflow-x: hidden;
  }
  &-item {
    justify-content: space-between;
    // border-top: 0.5px solid #e7e9e8;
    padding: 20 * 2px 0;
    &-left {
      flex: 1;
      &-img {
        margin-right: 12 * 2px;
        width: 40 * 2px;
        height: 40 * 2px;
        border-radius: 10 * 2px;
        border: 3px solid #fff;
        overflow: hidden;
      }
      &-title {
        color: #141924;
        font-size: 15 * 2px;
        font-weight: 590;
        margin-bottom: 6 * 2px;
        &-disabled {
          color: #999da7;
        }
      }
      &-desc {
        @include multi-line-omit(1);
        color: #999da7;
        font-size: 13 * 2px;
        &-disabled {
          color: #ced1d9;
        }
      }
    }
    &-right {
      border: 3px solid #d0d4df;
      border-radius: 100px;
      overflow: hidden;
      margin-left: 10 * 2px;
      &-center {
        margin: 2 * 2px;

        border-radius: 100px;
        width: 13 * 2px;
        height: 13 * 2px;
        &-disabled {
          margin: 0 !important;
          padding: 2 * 2px !important;
          box-sizing: content-box !important;
          background-color: #eceef3 !important;
          border: 3px solid #d0d4df !important;
        }
      }
    }
  }
}

.footer {
  padding: 12 * 2px 15 * 2px 32 * 2px 15 * 2px;
  justify-content: space-between;
  position: fixed;
  border-top: 3px solid #e7e9e8;
  background-color: #fff;
  width: 100vw;
  bottom: 33 * 2px;
  bottom: constant(safe-area-inset-bottom);
  bottom: env(safe-area-inset-bottom);

  &-btn {
    width: 100%;
    border-radius: 6 * 2px;
    background-color: #007bff;
    color: #fff;
    text-align: center;
    font-size: 15 * 2px;
    font-weight: 590;
    height: 48 * 2px;
    line-height: 48 * 2px;
    &-disabled {
      background-color: #B0D1F4;
    }
  }
}
.contentview {
  background-color: #f4f5f7;
  overflow-y: scroll;
  position: relative;
  &-notdata {
    justify-content: center;
    flex-direction: column;
    position: relative;
    top: 120 * 2px;
    &-img {
      width: 120 * 2px;
      height: 109 * 2px;
      margin-bottom: 5px;
    }
    &-desc {
      color: #999da7;
      font-size: 13 * 2px;
    }
    &-bg {
      background-color: #fff !important;
    }
  }
}
</style>
